package com.sunrise.gateway.shiro.redis;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import com.sunrise.gateway.commons.Constants;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheException;
import org.apache.shiro.cache.CacheManager;
import org.springframework.beans.factory.annotation.Autowired;

import com.dap.cache.common.RedisComponentInterface;
import org.springframework.beans.factory.annotation.Value;

/**
 * Edited by wangmin on 2017/6/13.
 */
public class RedisCacheManager implements CacheManager {
    private final ConcurrentMap<String, Cache> caches = new ConcurrentHashMap<String, Cache>();

    @Autowired
    private RedisComponentInterface jedis;

    @Value("${authentication.cache.expire.seconds}")
    private int authenticationCacheExpireSeconds;
    @Value("${authorization.cache.expire.seconds}")
    private int authorizationCacheExpireSeconds;
    @Value("${authRetry.cache.expire.seconds}")
    private int authRetryCacheExpireSeconds;
    @Value("${other.cache.expire.seconds}")
    private int otherCacheExpireSeconds;


    @Override
    public <K, V> Cache<K, V> getCache(String name) throws CacheException {
        Cache c = caches.get(name);
        if (c == null) {
            switch(name) {
                case "authenticationCache":
                    c = new RedisCache<K, V>(jedis, name, authenticationCacheExpireSeconds, SimpleAuthenticationInfo.class);
                    break;
                case "authorizationCache":
                    c = new RedisCache<K, V>(jedis, name, authorizationCacheExpireSeconds, SimpleAuthorizationInfo.class);
                    break;
                case Constants.AUTH_RETRIES_CACHE_NAME:
                    c = new RedisCache<K, V>(jedis, name, authRetryCacheExpireSeconds, Integer.class);
                    break;
                default:
                    c = new RedisCache<K, V>(jedis, name, otherCacheExpireSeconds, Object.class);
            }
            caches.put(name, c);
        }
        return c;
    }

}
